package com.lenovo.agricultureclient.request;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Element;

import com.lenovo.agricultureclient.AppConfig;
import com.lenovo.agricultureclient.util.Util;

/**
 * @author zongbingwu
 * 继承协议请求基类，因为本项目的服务器端大多情况会回应“result”键值对来表示请求是否成功，
 * 于是就创建了该类，主要处理只包含“result”键值对的返回结果
 *
 */
public abstract class AgricultureRequest extends BaseRequest 
{
	//存放服务器端的回应结果（成功或失败），基类只提供读取接口，具体内容由子类提供
	protected volatile boolean isSuccess = false; 
	
	public AgricultureRequest() 
	{
		super(AppConfig.PROTOCOL_TYPE);
	}
	
	//标记本次请求是否成功
	public boolean isSuccess() {
		return isSuccess;
	}

	//从jason回应报文中解析出“result”键值对
	@Override
	protected void onJasonParese(String responseStr) 
	{
		try 
		{
			JSONObject jsonRespObj = new JSONObject(responseStr);
			if(jsonRespObj != null)
			{
				if(jsonRespObj.has("result"))
				{
					String result = jsonRespObj.getString("result");
					result = result.toLowerCase();
					//“result”键值为"ok"则成功，否则失败
					if(result.equals("ok")){
						isSuccess = true;
					} else {
						isSuccess = false;
					}
				}
			}
		} 
		catch (JSONException e) 
		{
			isSuccess = false;
			e.printStackTrace();
		}
	}

	//从soap回应报文中解析出“result”键值对
	@Override
	protected void onSoapParese(String responseStr) 
	{
		String result = "";
		Element soapBodyEle = Util.getSoapBodyElement(responseStr);
		if(soapBodyEle != null)
		{
			result = Util.getChildElementValueStr(soapBodyEle, "result");
			result = result.toLowerCase();
		}
		//“result”键值为"ok"则成功，否则失败
		if(result.equals("ok")){
			isSuccess = true;
		} else {
			isSuccess = false;
		}
	}
	
}
